package controllers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	apiEndpoint = "https://api.openai.com/v1/engine/davinci-codex/completions"
	apiKey1     = "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"
	apiKey2     = "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"
)

type GPTRequest struct {
	Prompt      string  `json:"prompt"`
	MaxTokens   int     `json:"max_tokens"`
	Temperature float64 `json:"temperature"`
}

type GPTResponse struct {
	Choices []struct {
		Text string `json:"text"`
	} `json:"choices"`
}

func main() {
	// Create GPT request
	gptRequest := GPTRequest{
		Prompt:      "请用json格式回答我关于‘中国’的基本信息",
		MaxTokens:   1000,
		Temperature: 0.5,
	}

	// Create request payload
	payload, err := json.Marshal(gptRequest)
	if err != nil {
		fmt.Println("Error creating request payload:", err)
		return
	}

	// Create HTTP request
	req, err := http.NewRequest(http.MethodPost, apiEndpoint, bytes.NewBuffer(payload))
	if err != nil {
		fmt.Println("Error creating HTTP request:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey1)

	// Send HTTP request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending HTTP request:", err)
		return
	}
	defer resp.Body.Close()

	// Read response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// Parse response body
	var gptResp GPTResponse
	if err := json.Unmarshal(body, &gptResp); err != nil {
		fmt.Println("Error parsing response body:", err)
		return
	}

	// Print generated text
	if len(gptResp.Choices) == 0 {
		fmt.Println("No choices returned by GPT-3")
		return
	}
	fmt.Println(gptResp.Choices[0].Text)
}
